<template>
  <div>
    <!-- 主体头部组件 -->
    <Contentheader :headerInfo="headerInfo" :queryInfo="queryInfo" />

    <!-- 物品数据列表 -->
    <el-card>
      <template>
        <el-table
          :data="goodsList"
          tooltip-effect="dark"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="id" label="ID"> </el-table-column>
          <el-table-column prop="Productname" label="物品名称">
          </el-table-column>
          <el-table-column label="物品图片">
            <template slot-scope="scope">
              <el-image
                style="width: 50px; height: 50px"
                :src="scope.row.Productimage"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="物品状态">
            <template slot-scope="scope">
              <span v-if="scope.row.status">已领取</span>
              <span v-else>未领取</span>
            </template>
          </el-table-column>
          <el-table-column prop="fbtimer" label="发布时间" width="130px">
          </el-table-column>
          <el-table-column prop="IssueUser" label="发布人"> </el-table-column>
          <el-table-column prop="lqtimer" label="领取时间" width="130px">
          </el-table-column>
          <el-table-column prop="Username" label="领取人"> </el-table-column>
          <el-table-column prop="Phone" label="领取人电话"> </el-table-column>
          <el-table-column label="操作" width="110px">
            <template slot-scope="scope">
              <el-link type="primary" @click="editGoods(scope.row.id)"
                >编辑</el-link
              >
              <el-link
                class="btndel"
                type="danger"
                @click="delGoods(scope.row.id)"
                >删除</el-link
              >
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- 分页功能组件 -->
      <Pagination
        :queryInfo="queryInfo"
        :totalNum="totalNum"
        @getPageNo="getPageNo"
      />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑物品"
      :visible.sync="editGoodsVisible"
      width="50%"
      :before-close="handleClose"
    >
      <!-- 编辑物品表单 -->
      <el-form
        :model="goodsForm"
        :rules="goodsRules"
        ref="goodsRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="物品名称" prop="Productname">
          <el-input v-model="goodsForm.Productname"></el-input>
        </el-form-item>

        <!-- 图片上传 -->
        <el-form-item label="物品图片">
          <div class="demo-image">
            <div class="block">
              <span class="demonstration">原图</span>
              <el-image
                style="width: 100px; height: 100px"
                :src="oldImgSrc"
                :preview-src-list="[oldImgSrc]"
              ></el-image>
            </div>
            <div class="block">
              <span class="demonstration">修改图</span>
              <el-upload
                class="upload-demo imgbtn"
                action="http://localhost:8008/api/uploadImg"
                list-type="picture-card"
                :on-success="handleSuccess"
                :multiple="false"
                name="pic"
                ref="uploadImg"
              >
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{ file }">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                  />
                  <span class="el-upload-list__item-actions">
                    <!-- 查看 -->
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview"
                    >
                      <i class="el-icon-zoom-in"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
            </div>
          </div>
        </el-form-item>

        <!-- 物品描述 -->
        <el-form-item label="物品描述" prop="Describes">
          <el-input type="textarea" v-model="goodsForm.Describes"></el-input>
        </el-form-item>
        <!-- 发布人 -->
        <el-form-item label="发布人" prop="IssueUserid">
          <el-select
            v-model="goodsForm.IssueUserid"
            filterable
            placeholder="请选择发布人"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.Username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 领取人 -->
        <el-form-item
          label="领取人"
          prop="GetUserId"
          v-if="goodsForm.status != 0"
        >
          <el-select
            v-model="goodsForm.GetUserId"
            filterable
            placeholder="请选择领取人"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.Username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="editGoodsBtn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 内置对话框，图片预览 -->
    <el-dialog
      width="30%"
      title="物品图片预览"
      :visible.sync="innerVisible"
      append-to-body
      class="imgVisible"
    >
      <img :src="goodsForm.Productimage" alt="" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Contentheader from "@/components/Contentheader";
import Pagination from "@/components/Pagination";
export default {
  name: "Goodissus",
  data() {
    return {
      // Contentheader组件的数据
      headerInfo: {
        title: "发布物品管理",
        rightInfo: {
          btnName: "新增",
          iptMessage: "请输入物品名称",
        },
      },
      // 获取选中的数据
      multipleSelection: [],
      // 编辑对话框的显示和隐藏
      editGoodsVisible: false,
      // 物品图片预览的显示和隐藏
      innerVisible: false,
      // 编辑物品的数据
      goodsForm: {
        Productname: "", //物品名称
        Productimage: "", //物品图片
        Describes: "", // 物品描述
        IssueUserid: "", // 物品发布人
        GetUserId: "", //领取人id
      },
      // 保存原图地址
      oldImgSrc: "",
      // 表单验证规则
      goodsRules: {
        Productname: [
          { required: true, message: "请输入物品名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        Describes: [
          { required: true, message: "请输入物品描述", trigger: "blur" },
        ],
        IssueUserid: [
          { required: true, message: "请输选择发布人", trigger: "change" },
        ],
        GetUserId: [
          { required: true, message: "请输选择领取人", trigger: "change" },
        ],
      },

      //#region 分页功能
      // 获取用户列表的参数对象
      queryInfo: {
        // 当前第几页
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 3,
      },
      // 物品总数
      totalNum: 0,
      //#endregion
    };
  },
  components: { Contentheader, Pagination },
  mounted() {
    // 当页面刷新时发送请求获取数据
    this.getGoodsList(this.queryInfo);
    // 当页面刷新时获取物品总数
    this.$store.dispatch("goodissus/totalNumGoodsLists");
  },
  computed: {
    ...mapState("goodissus", [
      "goodsList",
      "delGoodMsg",
      "IdGoods",
      "updateGoodMsg",
      "totalGoods",
    ]),
    ...mapState("usermanage", ["userList"]),
  },
  methods: {
    // 物品信息页发送请求获取数据
    getGoodsList(queryInfo) {
      //console.log("要发送的数据：", queryInfo);
      this.$store.dispatch(
        "goodissus/getGoodsLists",
        JSON.stringify(queryInfo)
      );
    },
    // 删除功能
    delGoods(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.$store.dispatch("goodissus/delGoodsLists", id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //#region 编辑功能
    // 打开对话框事件
    editGoods(id) {
      this.$store.dispatch("goodissus/getIdGoodss", id);
      this.editGoodsVisible = true;
    },
    // 关闭对话框事件
    handleClose() {
      this.$refs.goodsRuleForm.resetFields(); //重置表单
      //移除图片
      let imglist = document.getElementsByClassName(
        "el-upload-list--picture-card"
      )[0];
      if (imglist.children.length >= 1) {
        imglist.removeChild(imglist.firstChild);
      }
      this.editGoodsVisible = false;
    },
    // 确定修改事件
    editGoodsBtn() {
      this.$refs.goodsRuleForm.validate((valid) => {
        if (!valid) {
          return false;
        }
        this.$store.dispatch(
          "goodissus/updateGoodss",
          JSON.stringify(this.goodsForm)
        );
        //console.log("修改之后：", this.goodsForm);
        this.handleClose();
      });
    },
    // 查看图片功能
    handlePictureCardPreview() {
      this.innerVisible = true;
    },
    // 监听图片上传成功的事件
    handleSuccess(response) {
      //移除上一次上传的图片
      let imglist = document.getElementsByClassName(
        "el-upload-list--picture-card"
      )[0];
      if (imglist.children.length >= 2) {
        imglist.removeChild(imglist.firstChild);
      }
      // 把图片路径保存起来
      this.goodsForm.Productimage =
        "http://localhost:8008/" +
        response.file.path.split("\\")[0] +
        "/" +
        response.file.path.split("\\")[1];
    },
    //#endregion

    // 自定义事件的回调函数--获取当前第几页
    getPageNo(queryInfo) {
      this.getGoodsList(queryInfo);
    },
    //全选按钮
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
  },
  watch: {
    //监听vuex中的数据变化
    // 删除按钮对应的数据
    delGoodMsg: {
      handler(newVal) {
        this.$message({
          type: "success",
          message: "删除成功!",
        });
        // 刷新页面
        this.getGoodsList(this.queryInfo);
        //重新获取物品条数
        this.$store.dispatch("goodissus/totalNumGoodsLists");
      },
    },
    // 编辑按钮对应的数据
    IdGoods: {
      handler(newVal) {
        // 获取要编辑的物品信息
        this.goodsForm = Object.assign(this.goodsForm, newVal[0]);
        // 保存原图地址
        this.oldImgSrc = this.goodsForm.Productimage;
      },
    },
    // 更新物品对应的提示
    updateGoodMsg: {
      handler(newVal) {
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        // 刷新页面
        this.getGoodsList(this.queryInfo);
      },
    },
    // 物品数目发生变化
    totalGoods: {
      handler(newVal) {
        this.totalNum = newVal[0].totalNum;
      },
    },
  },
};
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 20px;
  .btndel {
    margin-left: 10px;
  }
}
.imgbtn,
.el-select {
  float: left;
}
.imgVisible {
  text-align: center;
  .previewImg {
    max-height: 400px;
    max-width: 100%;
  }
}
.demo-image {
  display: flex;
  align-items: center;
}
.block {
  display: flex;
  flex-direction: column-reverse;
  margin-left: 20px;
}
.el-image {
  border-radius: 5px;
}
</style>
